#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id$
"""
XMLNews-to-Formatted text routines
"""
import os
import sys
from time import localtime, strftime, strptime, mktime
from xml.etree import cElementTree as ET


HEAD = ur"""<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css">
.container {
	margin: 0;
	padding: 0;
	list-style-type: none;
	font: 8pt Tahoma, Arial, Dejavu Sans, sans-serif;
	display: none; }
.container.root { display: block; }
.container[open] { display: block; }
.expand {
	width: 10px;
	height: 18px;
	min-height: 18px;
	float: left;
	background-image: url(chrome://global/skin/tree/twisty-clsd.png);
	background-position: center center;
	background-repeat: no-repeat; }
.expand[open] { background-image: url(chrome://global/skin/tree/twisty-open.png); }
.content {
	margin-left: 12px;
	padding-left: 20px;
	font-size: 8pt;
	min-height: 18px;
	background-position: left center;
	background-repeat: no-repeat; }
.root { margin-left: -18px; }
.node { margin-left: 16px; zoom: 1; }
.leaf { margin-left: 16px; zoom: 1; }
.date {
    background-image: url(chrome://browser/skin/places/calendar.png);}
.author {
    background-image: url(chrome://browser/skin/places/organize.png); }
.verse {
    background-image: url(chrome://browser/skin/Bookmarks-folder.png);
	margin-left: 20px;
	padding-left: 20px;
	font-size: 8pt;
	min-height: 18px;
	background-position: left center;
	background-repeat: no-repeat; }
.new { font-size: 70%; color: red; margin-right: 0.5em; }
.upd { font-size: 70%; color: blue; margin-right: 0.5em; }
.del { font-size: 70%; color: yellow; background: #555; padding: 0 0.2em; margin: 0 0.5em 0 0; }
</style>
<script type="text/javascript">
function doClick(event)
{
	 event = event || window.event;
	 var itm = event.target;
	 var node = itm.parentNode;
	 if (!hasClass(itm, 'expand') && !hasClass(itm, 'content')) { return; }

	 for (i=0;i<node.childNodes.length;i++)
	 {
	 	n = node.childNodes[i];
		if (hasClass(n, 'container') || hasClass(n, 'expand'))
		{
			if (n.hasAttribute('open')) { n.removeAttribute('open'); }
			else { n.setAttribute('open',''); }
		}
	 }
}

function hasClass(elem, className) {
    return new RegExp("(^|\\s)"+className+"(\\s|$)").test(elem.className)
}
</script>
</head><body>
<h3>Новости СИ</h3>
 <div onclick="doClick(arguments[0]);">
  <ul class="root container">
"""

FOOT = ur"""  </ul>
 </div>
</body></html>"""

DATE_HEAD = ur"""   <li class="node">
    <div class="expand">
    </div>
    <div class="content date">%(date)s</div>
     <ul class="container">
"""

DATE_FOOT = ur"""   </ul>
     </li>
"""

AUTHOR_HEAD = ur"""     <li class="node">
      <div class="expand">
      </div>
      <div class="content author"><a href="%(ahref)s" target="_blank">%(atitle)s</a>
      </div>
       <ul class="container">
"""

AUTHOR_FOOT = ur"""       </ul>
      </li>
"""


VERSE = ur"""        <li class="leaf verse">
         <span class="%(flag)s">%(flag)s</span><a href="%(href)s" target="_blank" title="%(date)s">%(title)s</a> %(gtitle)s &nbsp; <a href="../%(local_name)s" target="_blank">(local)</a> %(size)s %(diff_link)s %(size_diff)s
        </li>
"""

DIFF_LINK = ur"""<a href="../%(diff_name)s" target="_blank">[diff]</a>"""

def intdef(s, default=0):
	try:
		return int(s)
	except:
		return default

def floatdef(s, default=0.0):
	try:
		return float(s)
	except:
		return default


def news_for_date_htm(f, adate, anews, date_head=DATE_HEAD, date_foot=DATE_FOOT, author_head=AUTHOR_HEAD, author_foot=AUTHOR_FOOT, verse=VERSE, diff_link=DIFF_LINK):

	if adate:
		try:
			dt = strftime("%d.%m.%Y %H:%M:%S", localtime(adate))
		except:
			dt = '??.??.???? ??:??:??'
	else:
		dt = ''
	f.write((date_head % {'date':dt}).encode('utf-8','ignore'))

	news = [x for x in anews if x.scan_date==adate]
	auths = list(set([x.author[1].name for x in news]))
	auths.sort()
	for au in auths:
		vers = [x for x in news if x.author[1].name==au]
		# -- author --

		hdr = True
		for v in vers:
			#a = v.attrib.copy()
			a = {
				'flag':v.flagstr,
				'title':v.page[1].title,
				'atitle': v.author[1].name,
				'ahref': v.author[0],
				'href': v.page[0],
			}

			if v.size:
				if abs(v.size)>=1024: a['size'] = "%0.1fk" % (v.size*1.0/1024.0,)
				else: a['size'] = "%0d" % (v.size,)
			else:
				a['size'] = ''

			if v.size_diff:
				if abs(v.size_diff)>=1024: a['size_diff'] = "[%+0.1fk]" % (v.size_diff*1.0/1024.0,)
				else: a['size_diff'] = "[%+0d]" % (v.size_diff,)
			else:
				a['size_diff']=u''

			a['local_name'] = v.local_name.replace('\\','/') or ''
			a['diff_name'] = v.diff_name.replace('\\','/') or ''
			try:
				a['date'] = u"Обновлено: %s" % (strftime("%Y%m%dT%H:%M:%S",localtime(v.scan_date)),)
			except:
				a['date'] = u'Обновлено: ???'
			a['gtitle'] = u" (%s) " % (v.group_title,) if v.group_title else  u''

			a['diff_link'] = diff_link % a if (a['diff_name']) else ''


			if hdr:
				f.write((author_head % a).encode('utf-8','ignore'))
				hdr = False

			s = verse % a

			f.write(s.encode('utf-8','ignore'))
		# -- author footer --
		f.write(author_foot.encode('utf-8','ignore'))

	f.write(date_foot.encode('utf-8','ignore'))



def news_htm(f, news_list, htm_header=HEAD, htm_footer=FOOT, \
			  date_head=DATE_HEAD, date_foot=DATE_FOOT, \
			  author_head=AUTHOR_HEAD, author_foot=AUTHOR_FOOT, \
			  verse=VERSE, diff_link=DIFF_LINK):
	"""
	Make formatted news page from pased list of news and templates
	"""

	dates = list(set([x.scan_date for x in news_list]))
	dates.sort(reverse=True)
	f.write(htm_header.encode('utf-8', 'ignore'))

	for d in dates:
		news_for_date_htm(f, d, news_list, date_head, date_foot, author_head, author_foot, verse, diff_link)

	f.write(htm_footer.encode('utf-8', 'ignore'))


def authors_htm(f, db):
	#TODO: make tree of all authors with verses per-author
	pass

if __name__ == "__main__":
	import siglobals
	from siglobals import cfg
	from sicfg import init
	from db.sixml import XMLdb


	arg = init()

	if not os.path.exists(cfg['base']):
		try:
			os.makedirs(os.path.split(cfg['base'])[0])
		except:
			pass
	db = XMLdb(cfg['base'])
	db.load_news(cfg['news'])

	f = sys.stdout
	if len(sys.argv)>1:
		f = open(sys.argv[1],'wb')
	try:
		news_htm(f, db.news)
	finally:
		if f != sys.stdout: f.close()

